<template>
  <div class="home">
    <h1> {{reconnecting? "连接成功":"正在重新连接" }}</h1>
  <input id="soto"  :value="message">
    <button @click="send"> 发送</button>
    <h2>{{tableData}}</h2>
  </div>
</template>

<script>
import request from "@/request";
import * as SockJS from "sockjs-client";
import * as Stomp from "stompjs";

export default {
  name: "home",
  data() {
    return {
      str: '未连接',
      url : 'http://localhost:9000/webSocket/stmp',
      reconnecting: false,
      overWS: null,
      socket: null,
      message: '123',
      tableData:'1'
    }
  },
  created() {
  this.info()
  },
  methods: {
    info() {
      this.socket = new SockJS(this.url)
      console.log("socket ",this.socket)
      this.overWS = Stomp.over(this.socket);
      console.log("overWS ",this.overWS)
      //第一个参数携带头部信息 headers  一般用于认证
      this.overWS.connect({}, (frame) => {

        //进入此方法表示连接成功
        console.log("frame"+frame)
        this.connectSucceed()
      },err => {
        // 连接失败的回调
        this.reconnect(this.url, this.connectSucceed)
          })
    },

    //回调方法
    connectSucceed () {
      this.reconnecting = true;
      this.str = '连接成功!'
      // 设置心跳发送接受频率（ms）默认为10000ms。 heart-beating是利用window.setInterval()去规律地发送heart-beats或者检查服务端的heart-beats。
      this.overWS.heartbeat.outgoing = 10000
      this.overWS.heartbeat.incoming = 0

      this.overWS.subscribe('/topic/stomp/data', res => {
        console.log("收到的消息是: ",res)
        this.tableData = res.body
      })

      /*
      当客户端与服务端连接成功后，可以调用 send()来发送STOMP消息。这个方法必须有一个参数，用来描述对应的STOMP的目的地。
      另外可以有两个可选的参数：headers，object类型包含额外的信息头部；body，一个String类型的参数。

      client.send("/queue/test", {priority: 9}, "Hello, STOMP");
      // client会发送一个STOMP发送帧给/queue/test，这个帧包含一个设置了priority为9的header和内容为“Hello, STOMP”的body。
      */
    //  this.stompClient.send('/topic/dashboard/send',{}, '1')
    },


    //发送方法
    send(){
      console.log(this.message)
      //request.get("/stomp/soket/"+this.message);
        var elementById = document.getElementById("soto");
      console.log()

      this.overWS.send('/app/send',{},JSON.stringify({"message":elementById.value}))
    },

    reconnect (socketUrl, callback) {
      this.reconnecting = false;
      let connected = false
      const timer = setInterval(() => {
        console.log("正在重新连接!!!!")
        this.socket = new SockJS(socketUrl)
        this.overWS = Stomp.over(this.socket)
        this.overWS.connect({}, frame => {

          connected = true
          clearInterval(timer)
          callback()
        }, err => {
          console.log('Reconnect failed！');
          if(!connected) console.log(err);
        })
      }, 1000);
    },

  //关闭连接
    closeSocket(){
      if(this.stompClient != null){
        this.stompClient.disconnect()
        // this.stompClient.disconnect(()=>{
        //   console.log('连接关闭')
        // });
      }
    },
  }
}
//export default class HomeView extends Vue {}
</script>